<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>五子棋在线对战 - 管理后台</title>
    <link rel="stylesheet" href="common.css">
    <style>
        body {
            background: #f8f9fa;
            margin: 0;
            font-family: 'Microsoft YaHei', Arial, sans-serif;
        }
        
        .header {
            background: #2c3e50;
            color: white;
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .header h1 {
            font-size: 18px;
            font-weight: bold;
        }
        
        .header-actions {
            display: flex;
            gap: 10px;
            align-items: center;
        }
        
        .admin-info {
            font-size: 14px;
            margin-right: 15px;
        }
        
        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }
        
        .btn-primary {
            background: #3498db;
            color: white;
        }
        
        .btn-danger {
            background: #e74c3c;
            color: white;
        }
        
        .main-container {
            display: flex;
            min-height: calc(100vh - 70px);
        }
        
        .sidebar {
            width: 250px;
            background: white;
            box-shadow: 2px 0 10px rgba(0,0,0,0.1);
            padding: 20px 0;
        }
        
        .menu-item {
            padding: 15px 20px;
            cursor: pointer;
            transition: all 0.3s ease;
            border-left: 3px solid transparent;
        }
        
        .menu-item:hover {
            background: #f8f9fa;
        }
        
        .menu-item.active {
            background: #e8f4f8;
            border-left-color: #3498db;
            color: #3498db;
            font-weight: bold;
        }
        
        .content-area {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
        }
        
        .module {
            display: none;
        }
        
        .module.active {
            display: block;
        }
        
        .card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .card-title {
            font-size: 18px;
            font-weight: bold;
            color: #2c3e50;
            margin-bottom: 20px;
        }
        
        .search-box {
            width: 100%;
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
            margin-bottom: 20px;
        }
        
        .search-box:focus {
            outline: none;
            border-color: #3498db;
        }
        
        .table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .table th,
        .table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ecf0f1;
        }
        
        .table th {
            background: #f8f9fa;
            font-weight: bold;
            color: #2c3e50;
        }
        
        .status-badge {
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
        }
        
        .status-normal {
            background: #d5f4e6;
            color: #27ae60;
        }
        
        .status-disabled {
            background: #fadbd8;
            color: #e74c3c;
        }
        
        .action-btn {
            padding: 6px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            margin-right: 5px;
        }
        
        .btn-enable {
            background: #27ae60;
            color: white;
        }
        
        .btn-disable {
            background: #e74c3c;
            color: white;
        }
        
        .btn-view {
            background: #3498db;
            color: white;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #2c3e50;
        }
        
        .form-input,
        .form-select {
            width: 100%;
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
        }
        
        .form-input:focus,
        .form-select:focus {
            outline: none;
            border-color: #3498db;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: linear-gradient(135deg, #3498db, #2980b9);
            color: white;
            padding: 20px;
            border-radius: 12px;
            text-align: center;
        }
        
        .stat-value {
            font-size: 32px;
            font-weight: bold;
            margin: 10px 0;
        }
        
        .stat-label {
            font-size: 14px;
            opacity: 0.9;
        }
        
        .chart-container {
            height: 300px;
            margin: 20px 0;
        }
        
        .chart-placeholder {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100%;
            background: #f8f9fa;
            border-radius: 8px;
            color: #7f8c8d;
        }
        
        .date-filter {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            align-items: center;
        }
        
        .date-input {
            padding: 8px;
            border: 2px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
        }
        
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 15px;
            margin-top: 20px;
        }
        
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }
        
        .modal.show {
            display: flex;
        }
        
        .modal-content {
            background: white;
            border-radius: 12px;
            padding: 30px;
            max-width: 600px;
            width: 90%;
            max-height: 80vh;
            overflow-y: auto;
        }
        
        .modal-title {
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 20px;
            color: #2c3e50;
        }
        
        @media (max-width: 768px) {
            .main-container {
                flex-direction: column;
            }
            
            .sidebar {
                width: 100%;
                display: flex;
                overflow-x: auto;
            }
            
            .menu-item {
                white-space: nowrap;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>五子棋在线对战 - 管理后台</h1>
        <div class="header-actions">
            <span class="admin-info">管理员: admin</span>
            <button class="btn btn-primary" onclick="backToLobby()">返回大厅</button>
            <button class="btn btn-danger" onclick="logout()">退出登录</button>
        </div>
    </div>
    
    <div class="main-container">
        <div class="sidebar">
            <div class="menu-item active" onclick="switchModule('users')">用户管理</div>
            <div class="menu-item" onclick="switchModule('points')">积分管理</div>
            <div class="menu-item" onclick="switchModule('stats')">数据统计</div>
        </div>
        
        <div class="content-area">
            <!-- 用户管理模块 -->
            <div id="usersModule" class="module active">
                <div class="card">
                    <div class="card-title">用户管理</div>
                    <input type="text" class="search-box" id="userSearch" placeholder="搜索账号或昵称..." oninput="searchUsers()">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>账号</th>
                                <th>昵称</th>
                                <th>积分</th>
                                <th>总场次</th>
                                <th>胜场</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="userTableBody">
                            <!-- 用户列表将通过JavaScript动态生成 -->
                        </tbody>
                    </table>
                    <div class="pagination">
                        <button class="btn btn-primary" onclick="changeUserPage(-1)">上一页</button>
                        <span id="userPageInfo">第 1 页，共 1 页</span>
                        <button class="btn btn-primary" onclick="changeUserPage(1)">下一页</button>
                    </div>
                </div>
            </div>
            
            <!-- 积分管理模块 -->
            <div id="pointsModule" class="module">
                <div class="card">
                    <div class="card-title">积分调整</div>
                    <form id="pointsForm" onsubmit="adjustPoints(event)">
                        <div class="form-group">
                            <label class="form-label">用户搜索</label>
                            <input type="text" class="form-input" id="pointsUserSearch" placeholder="输入账号或昵称搜索用户">
                        </div>
                        <div class="form-group">
                            <label class="form-label">积分调整类型</label>
                            <select class="form-select" id="pointsType" required>
                                <option value="add">增加</option>
                                <option value="subtract">减少</option>
                                <option value="set">设置为</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label class="form-label">积分数量</label>
                            <input type="number" class="form-input" id="pointsAmount" placeholder="请输入积分数量" required min="0">
                        </div>
                        <div class="form-group">
                            <label class="form-label">调整原因</label>
                            <input type="text" class="form-input" id="pointsReason" placeholder="请输入调整原因" required>
                        </div>
                        <button type="submit" class="btn btn-primary">提交</button>
                    </form>
                </div>
                
                <div class="card">
                    <div class="card-title">操作日志</div>
                    <div class="date-filter">
                        <input type="date" class="date-input" id="logStartDate">
                        <span>至</span>
                        <input type="date" class="date-input" id="logEndDate">
                        <button class="btn btn-primary" onclick="filterLogs()">筛选</button>
                    </div>
                    <table class="table">
                        <thead>
                            <tr>
                                <th>时间</th>
                                <th>操作员</th>
                                <th>用户</th>
                                <th>调整类型</th>
                                <th>数量</th>
                                <th>原因</th>
                            </tr>
                        </thead>
                        <tbody id="logTableBody">
                            <!-- 日志列表将通过JavaScript动态生成 -->
                        </tbody>
                    </table>
                    <div class="pagination">
                        <button class="btn btn-primary" onclick="changeLogPage(-1)">上一页</button>
                        <span id="logPageInfo">第 1 页，共 1 页</span>
                        <button class="btn btn-primary" onclick="changeLogPage(1)">下一页</button>
                    </div>
                </div>
            </div>
            
            <!-- 数据统计模块 -->
            <div id="statsModule" class="module">
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-label">总用户数</div>
                        <div class="stat-value" id="totalUsers">1,234</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-label">在线人数</div>
                        <div class="stat-value" id="onlineUsers">567</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-label">今日对局数</div>
                        <div class="stat-value" id="todayMatches">89</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-label">总对局数</div>
                        <div class="stat-value" id="totalMatches">12,345</div>
                    </div>
                </div>
                
                <div class="card">
                    <div class="card-title">用户增长趋势图</div>
                    <div class="date-filter">
                        <select class="form-select" id="statsDimension" style="width: auto;">
                            <option value="day">按日</option>
                            <option value="week">按周</option>
                            <option value="month">按月</option>
                        </select>
                        <input type="date" class="date-input" id="statsStartDate">
                        <span>至</span>
                        <input type="date" class="date-input" id="statsEndDate">
                        <button class="btn btn-primary" onclick="updateStats()">更新</button>
                    </div>
                    <div class="chart-container">
                        <canvas id="userGrowthChart" width="800" height="300"></canvas>
                    </div>
                </div>
                
                <div class="card">
                    <div class="card-title">对局统计图</div>
                    <div class="chart-container">
                        <canvas id="matchStatsChart" width="800" height="300"></canvas>
                    </div>
                </div>
                
                <div class="card">
                    <div class="card-title">积分分布图</div>
                    <div class="chart-container">
                        <canvas id="pointsDistributionChart" width="600" height="300"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 用户详情弹窗 -->
    <div id="userDetailModal" class="modal">
        <div class="modal-content">
            <div class="modal-title">用户详情</div>
            <div id="userDetailContent">
                <!-- 用户详情内容将通过JavaScript动态生成 -->
            </div>
            <div style="margin-top: 20px; text-align: right;">
                <button class="btn btn-primary" onclick="closeUserDetailModal()">关闭</button>
            </div>
        </div>
    </div>

    <script>
        // 模拟数据
        const userData = [
            { id: 1, username: 'user001', nickname: '玩家001', points: 150, totalMatches: 25, wins: 18, status: 'normal' },
            { id: 2, username: 'user002', nickname: '玩家002', points: 145, totalMatches: 20, wins: 12, status: 'normal' },
            { id: 3, username: 'user003', nickname: '玩家003', points: 160, totalMatches: 30, wins: 20, status: 'disabled' },
            { id: 4, username: 'user004', nickname: '玩家004', points: 140, totalMatches: 15, wins: 8, status: 'normal' },
            { id: 5, username: 'user005', nickname: '玩家005', points: 155, totalMatches: 22, wins: 15, status: 'normal' },
        ];
        
        const logData = [
            { time: '2024-01-15 14:30', operator: 'admin', user: '玩家001', type: '增加', amount: 10, reason: '活动奖励' },
            { time: '2024-01-15 13:20', operator: 'admin', user: '玩家003', type: '减少', amount: 5, reason: '违规处罚' },
            { time: '2024-01-14 16:45', operator: 'admin', user: '玩家002', type: '设置为', amount: 150, reason: '数据修正' },
        ];
        
        let currentUserPage = 1;
        let currentLogPage = 1;
        let filteredUsers = [...userData];
        let filteredLogs = [...logData];
        
        // 切换模块
        function switchModule(moduleName) {
            document.querySelectorAll('.module').forEach(m => m.classList.remove('active'));
            document.querySelectorAll('.menu-item').forEach(m => m.classList.remove('active'));
            
            document.getElementById(moduleName + 'Module').classList.add('active');
            event.target.classList.add('active');
            
            if (moduleName === 'stats') {
                initStatsCharts();
            }
        }
        
        // 加载用户列表
        function loadUsers() {
            const tbody = document.getElementById('userTableBody');
            const startIndex = (currentUserPage - 1) * 10;
            const endIndex = startIndex + 10;
            const pageData = filteredUsers.slice(startIndex, endIndex);
            
            tbody.innerHTML = '';
            pageData.forEach(user => {
                const row = document.createElement('tr');
                const statusClass = user.status === 'normal' ? 'status-normal' : 'status-disabled';
                const statusText = user.status === 'normal' ? '正常' : '已禁用';
                const actionBtn = user.status === 'normal' 
                    ? `<button class="action-btn btn-disable" onclick="toggleUserStatus(${user.id})">禁用</button>`
                    : `<button class="action-btn btn-enable" onclick="toggleUserStatus(${user.id})">启用</button>`;
                
                row.innerHTML = `
                    <td>${user.username}</td>
                    <td>${user.nickname}</td>
                    <td>${user.points}</td>
                    <td>${user.totalMatches}</td>
                    <td>${user.wins}</td>
                    <td><span class="status-badge ${statusClass}">${statusText}</span></td>
                    <td>
                        ${actionBtn}
                        <button class="action-btn btn-view" onclick="viewUserDetail(${user.id})">查看详情</button>
                    </td>
                `;
                tbody.appendChild(row);
            });
            
            const totalPages = Math.ceil(filteredUsers.length / 10);
            document.getElementById('userPageInfo').textContent = `第 ${currentUserPage} 页，共 ${totalPages} 页`;
        }
        
        // 搜索用户
        function searchUsers() {
            const keyword = document.getElementById('userSearch').value.toLowerCase();
            filteredUsers = userData.filter(user => 
                user.username.toLowerCase().includes(keyword) || 
                user.nickname.toLowerCase().includes(keyword)
            );
            currentUserPage = 1;
            loadUsers();
        }
        
        // 切换用户状态
        function toggleUserStatus(userId) {
            const user = userData.find(u => u.id === userId);
            if (user) {
                user.status = user.status === 'normal' ? 'disabled' : 'normal';
                if (confirm(`确定要${user.status === 'normal' ? '启用' : '禁用'}该用户吗？`)) {
                    loadUsers();
                    alert('操作成功！');
                }
            }
        }
        
        // 查看用户详情
        function viewUserDetail(userId) {
            const user = userData.find(u => u.id === userId);
            if (user) {
                const modal = document.getElementById('userDetailModal');
                const content = document.getElementById('userDetailContent');
                content.innerHTML = `
                    <div style="margin-bottom: 15px;">
                        <strong>账号:</strong> ${user.username}
                    </div>
                    <div style="margin-bottom: 15px;">
                        <strong>昵称:</strong> ${user.nickname}
                    </div>
                    <div style="margin-bottom: 15px;">
                        <strong>积分:</strong> ${user.points}
                    </div>
                    <div style="margin-bottom: 15px;">
                        <strong>总场次:</strong> ${user.totalMatches}
                    </div>
                    <div style="margin-bottom: 15px;">
                        <strong>胜场:</strong> ${user.wins}
                    </div>
                    <div style="margin-bottom: 15px;">
                        <strong>状态:</strong> ${user.status === 'normal' ? '正常' : '已禁用'}
                    </div>
                `;
                modal.classList.add('show');
            }
        }
        
        function closeUserDetailModal() {
            document.getElementById('userDetailModal').classList.remove('show');
        }
        
        // 积分调整
        function adjustPoints(event) {
            event.preventDefault();
            const type = document.getElementById('pointsType').value;
            const amount = parseInt(document.getElementById('pointsAmount').value);
            const reason = document.getElementById('pointsReason').value;
            const user = document.getElementById('pointsUserSearch').value;
            
            if (!user) {
                alert('请先搜索并选择用户');
                return;
            }
            
            if (confirm(`确定要${type === 'add' ? '增加' : type === 'subtract' ? '减少' : '设置为'} ${amount} 积分吗？`)) {
                // 添加到日志
                logData.unshift({
                    time: new Date().toLocaleString('zh-CN'),
                    operator: 'admin',
                    user: user,
                    type: type === 'add' ? '增加' : type === 'subtract' ? '减少' : '设置为',
                    amount: amount,
                    reason: reason
                });
                
                // 重置表单
                document.getElementById('pointsForm').reset();
                loadLogs();
                alert('积分调整成功！');
            }
        }
        
        // 加载日志
        function loadLogs() {
            const tbody = document.getElementById('logTableBody');
            const startIndex = (currentLogPage - 1) * 10;
            const endIndex = startIndex + 10;
            const pageData = filteredLogs.slice(startIndex, endIndex);
            
            tbody.innerHTML = '';
            pageData.forEach(log => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${log.time}</td>
                    <td>${log.operator}</td>
                    <td>${log.user}</td>
                    <td>${log.type}</td>
                    <td>${log.amount}</td>
                    <td>${log.reason}</td>
                `;
                tbody.appendChild(row);
            });
            
            const totalPages = Math.ceil(filteredLogs.length / 10);
            document.getElementById('logPageInfo').textContent = `第 ${currentLogPage} 页，共 ${totalPages} 页`;
        }
        
        // 筛选日志
        function filterLogs() {
            const startDate = document.getElementById('logStartDate').value;
            const endDate = document.getElementById('logEndDate').value;
            
            if (startDate && endDate) {
                filteredLogs = logData.filter(log => {
                    const logDate = log.time.split(' ')[0];
                    return logDate >= startDate && logDate <= endDate;
                });
            } else {
                filteredLogs = [...logData];
            }
            
            currentLogPage = 1;
            loadLogs();
        }
        
        // 初始化统计图表
        function initStatsCharts() {
            // 用户增长趋势图
            const growthCtx = document.getElementById('userGrowthChart').getContext('2d');
            drawLineChart(growthCtx, [100, 150, 200, 250, 300, 350, 400], '用户增长趋势');
            
            // 对局统计图
            const matchCtx = document.getElementById('matchStatsChart').getContext('2d');
            drawBarChart(matchCtx, [50, 60, 70, 65, 80, 75, 89], '每日对局数');
            
            // 积分分布图
            const pointsCtx = document.getElementById('pointsDistributionChart').getContext('2d');
            drawPieChart(pointsCtx, [
                { label: '0-100分', value: 200 },
                { label: '101-150分', value: 500 },
                { label: '151-200分', value: 300 },
                { label: '200分以上', value: 234 }
            ]);
        }
        
        // 绘制折线图
        function drawLineChart(ctx, data, title) {
            const width = ctx.canvas.width;
            const height = ctx.canvas.height;
            const padding = 40;
            const chartWidth = width - padding * 2;
            const chartHeight = height - padding * 2;
            const maxValue = Math.max(...data);
            
            ctx.clearRect(0, 0, width, height);
            ctx.strokeStyle = '#3498db';
            ctx.lineWidth = 2;
            ctx.beginPath();
            
            data.forEach((value, index) => {
                const x = padding + (index / (data.length - 1)) * chartWidth;
                const y = padding + chartHeight - (value / maxValue) * chartHeight;
                if (index === 0) {
                    ctx.moveTo(x, y);
                } else {
                    ctx.lineTo(x, y);
                }
            });
            ctx.stroke();
        }
        
        // 绘制柱状图
        function drawBarChart(ctx, data, title) {
            const width = ctx.canvas.width;
            const height = ctx.canvas.height;
            const padding = 40;
            const chartWidth = width - padding * 2;
            const chartHeight = height - padding * 2;
            const maxValue = Math.max(...data);
            const barWidth = chartWidth / data.length - 10;
            
            ctx.clearRect(0, 0, width, height);
            ctx.fillStyle = '#3498db';
            
            data.forEach((value, index) => {
                const x = padding + index * (chartWidth / data.length) + 5;
                const barHeight = (value / maxValue) * chartHeight;
                const y = padding + chartHeight - barHeight;
                ctx.fillRect(x, y, barWidth, barHeight);
            });
        }
        
        // 绘制饼图
        function drawPieChart(ctx, data) {
            const width = ctx.canvas.width;
            const height = ctx.canvas.height;
            const centerX = width / 2;
            const centerY = height / 2;
            const radius = Math.min(width, height) / 2 - 40;
            
            const total = data.reduce((sum, item) => sum + item.value, 0);
            const colors = ['#3498db', '#27ae60', '#f39c12', '#e74c3c'];
            
            ctx.clearRect(0, 0, width, height);
            
            let currentAngle = -Math.PI / 2;
            data.forEach((item, index) => {
                const sliceAngle = (item.value / total) * 2 * Math.PI;
                ctx.beginPath();
                ctx.moveTo(centerX, centerY);
                ctx.arc(centerX, centerY, radius, currentAngle, currentAngle + sliceAngle);
                ctx.closePath();
                ctx.fillStyle = colors[index % colors.length];
                ctx.fill();
                currentAngle += sliceAngle;
            });
        }
        
        function updateStats() {
            initStatsCharts();
            alert('统计数据已更新');
        }
        
        function changeUserPage(direction) {
            const newPage = currentUserPage + direction;
            const totalPages = Math.ceil(filteredUsers.length / 10);
            if (newPage >= 1 && newPage <= totalPages) {
                currentUserPage = newPage;
                loadUsers();
            }
        }
        
        function changeLogPage(direction) {
            const newPage = currentLogPage + direction;
            const totalPages = Math.ceil(filteredLogs.length / 10);
            if (newPage >= 1 && newPage <= totalPages) {
                currentLogPage = newPage;
                loadLogs();
            }
        }
        
        function backToLobby() {
            window.location.href = 'lobby.html';
        }
        
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                window.location.href = 'login.html';
            }
        }
        
        // 点击遮罩层关闭弹窗
        document.getElementById('userDetailModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeUserDetailModal();
            }
        });
        
        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadUsers();
            loadLogs();
        });
    </script>
</body>
</html>

